import WxRequest from 'mina-request'
import {toast,modal} from './API'
import {clreaStorage,setStorage,getStorage} from './storage'
import {env} from './env'
//对类进行实例化
const instance = new WxRequest({
      baseURL:env.baseURL,
      timeout:15000
})

//请求拦截器:请求发送之前
instance.interceptors.request = (config) =>{
        const token =getStorage('token')
        if(token){
          config.header['token'] = token
        }
        return config
}

//响应拦截器：服务器响应数据后
instance.interceptors.response = (response)=>{
  //response中解构两个数据
  const {isSuccess,data} = response

  if(!isSuccess){
        toast({
              title:'网络异常请重试',
              icon:'error'
        })
        return Promise.reject(response)
  }
switch(data.code){
  case 200:
    return data
  case 208:
   const res =  modal({
      content:'请重新登录',
      showCancel:false
   })

   if(res){
    clreaStorage()

    wx.navigateTo({
      url: '/pages/home/home.wxml',
    })
   }
   return Promise.reject(response)
}
  return response
}

export default instance